package com.chunayev.numerology.gui.table.listener;

import java.util.ArrayList;
import java.util.Arrays;

import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import com.chunayev.numerology.gui.table.NameCalculationsTable;
import com.chunayev.numerology.gui.table.NumerologicTable;
import com.chunayev.numerology.util.Constants;

/**
 * @author Sergey Chunayev
 */
public class StatisticsTableSelectionListener implements ListSelectionListener {
    private final NumerologicTable numerologicTable;
    private final NameCalculationsTable statisticsTable;
    private final NameCalculationsTable tokensStatisticsTable;
    
    /**
     * @param numerologicTable
     * @param statisticsTable
     * @param tokensStatisticsTable
     */
    public StatisticsTableSelectionListener(NumerologicTable numerologicTable,
            NameCalculationsTable statisticsTable,
            NameCalculationsTable tokensStatisticsTable) {
        super();
        this.numerologicTable = numerologicTable;
        this.statisticsTable = statisticsTable;
        this.tokensStatisticsTable = tokensStatisticsTable;
    }
    
    /*
     * (non-Javadoc)
     * @see
     * javax.swing.event.ListSelectionListener#valueChanged(javax.swing.event
     * .ListSelectionEvent)
     */
    @Override
    public void valueChanged(final ListSelectionEvent e) {
        if (!e.getValueIsAdjusting()) {
            final int index = statisticsTable.getSelectedRow();
            if (index != -1) {
                final String value = statisticsTable
                        .<String> getGenericValueAt(index, 0);
                final int position = statisticsTable
                        .<Integer> getGenericValueAt(index, 2);
                numerologicTable.setMainPosition(position);
                
                final String[] tokens = value.trim().split(Constants.REGEXP);
                
                tokensStatisticsTable.getModel().setData(Arrays.asList(tokens));
                numerologicTable.setMainToolTip(value);
                
            } else {
                tokensStatisticsTable.getModel().setData(
                        new ArrayList<String>());
                numerologicTable.setMainPosition(-1);
            }
            
            numerologicTable.repaint();
        }
    }
    
}
